package com.share.tool;

import java.util.*;

/**
 * author:caifan
 * date:2019/12/19
 */
public class StringReplaceUtil {
    private static final String PREFIX = "${";
    private static final String SUFFIX = "}";

    public static void main(String[] args) throws Exception {
        String str = "abc${ab}ede${de}bd${dd}a";
        Map<String, String> valueMap = new HashMap<>();
        valueMap.put("ab", "AB");
        valueMap.put("de", "DE");
        valueMap.put("dd", "DD");
        System.out.println(parseString(str, valueMap));
    }

    public static String parseString(String str, Map<String, String> valueMap) throws Exception {
        Map<String, String> originMap = new HashMap<>();
        Map<Integer, Integer> map = checkString(str);
        for (Map.Entry<Integer, Integer> kv : map.entrySet()) {
            int start = kv.getKey();
            int end = kv.getValue();
            String orginStr;
            String subStr;
            if (end + 1 >= str.length()) {
                orginStr = str.substring(start);
            } else {
                orginStr = str.substring(start, end + 1);
            }
            subStr = str.substring(start + PREFIX.length(), end);
            originMap.put(subStr, orginStr);
        }

        for (Map.Entry<String, String> kv : valueMap.entrySet()) {
            str = str.replace(originMap.get(kv.getKey()), kv.getValue());
        }
        return str;
    }

    private static Map<Integer, Integer> checkString(String str) throws Exception {
        int strLen = str.length();
        int index = 0;
        List<Integer> prefixList = new ArrayList<>();
        List<Integer> suffixList = new ArrayList<>();
        while (index < strLen) {
            index = str.indexOf(PREFIX, index);
            if (index < 0) {
                break;
            }
            prefixList.add(index);
            index = index + PREFIX.length();
        }
        index = 0;

        while (index < strLen) {
            index = str.indexOf(SUFFIX, index);
            if (index < 0) {
                break;
            }
            suffixList.add(index);
            index = index + SUFFIX.length();
        }
        if (prefixList.size() != suffixList.size()) {
            throw new Exception("prefix suffix size not equals");
        }

        Map<Integer, Integer> map = new LinkedHashMap();
        for (int i=0;i<prefixList.size();i++) {
            map.put(prefixList.get(i), suffixList.get(i));
        }
        return map;

    }
}
